#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修复表单选项加载时序问题
问题：编辑客户时，行业类型和客户来源显示ID而非文字
原因：表单数据在选项加载前就初始化，导致下拉框无法匹配到正确的label
解决：监听表单数据变化，在数据填充后检查并重新渲染
"""

import re

def fix_form_options_loading():
    # 修复 EnterpriseInfoForm.vue
    enterprise_file = 'frontend/src/views/crm/components/customer_form/EnterpriseInfoForm.vue'

    with open(enterprise_file, 'r', encoding='utf-8') as f:
        content = f.read()

    # 添加watch监听formData变化
    new_script = '''<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { customerApi } from '@/api/crm'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const formData = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 行业选项 - 从API获取
const industryOptions = ref<Array<{ value: number; label: string }>>([])
const loading = ref(false)

// 从API获取行业选项
const loadIndustryOptions = async () => {
  if (loading.value) return

  loading.value = true
  try {
    const response = await customerApi.industryOptions()
    console.log('行业选项API返回数据:', response)
    if (response.code === 0 && response.data) {
      industryOptions.value = response.data
      console.log('行业选项列表:', industryOptions.value)
    } else {
      ElMessage.error('获取行业选项失败')
    }
  } catch (error) {
    console.error('获取行业选项失败:', error)
    ElMessage.error('获取行业选项失败')
  } finally {
    loading.value = false
  }
}

// 监听表单数据变化，当填充数据后重新检查行业字段
watch(() => formData.value.industry, (newVal, oldVal) => {
  console.log('行业字段变化:', oldVal, '->', newVal)
  // 如果有值但选项还没加载，则强制加载选项
  if (newVal && industryOptions.value.length === 0) {
    loadIndustryOptions()
  }
})

// 监听customer_type变化，确保企业客户时加载行业选项
watch(() => formData.value.customer_type, (newVal) => {
  if (newVal === 2 && industryOptions.value.length === 0) {
    loadIndustryOptions()
  }
})

// 组件挂载时加载行业选项
onMounted(() => {
  loadIndustryOptions()
})
</script>'''

    # 替换script部分
    content = re.sub(
        r'<script setup lang="ts">.*?</script>',
        new_script,
        content,
        flags=re.DOTALL
    )

    with open(enterprise_file, 'w', encoding='utf-8') as f:
        f.write(content)

    print("✅ EnterpriseInfoForm.vue 修复完成")
    print("   - 添加了watch监听formData.industry变化")
    print("   - 添加了watch监听customer_type变化")
    print("   - 确保选项数据加载后再渲染表单")

    # 同样修复 BasicInfoForm.vue（虽然sourceOptions看起来已经正确，但为了保险起见）
    basic_file = 'frontend/src/views/crm/components/customer_form/BasicInfoForm.vue'

    with open(basic_file, 'r', encoding='utf-8') as f:
        content = f.read()

    # 添加watch监听
    new_script_basic = '''<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { customerApi } from '@/api/crm'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

// 双向绑定
const formData = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 数据列表
const userList = ref<Array<{ value: number; label: string; department_id?: number }>>([])
const deptList = ref<Array<{ value: number; label: string }>>([])
const sourceOptions = ref<Array<{ value: string; label: string }>>([])

// 加载数据
const loadOptions = async () => {
  try {
    // 加载负责人列表
    const userRes = await customerApi.userOptions()
    userList.value = userRes.data || []

    // 加载部门列表
    const deptRes = await customerApi.departmentOptions()
    deptList.value = deptRes.data || []

    // 加载客户来源
    const sourceRes = await customerApi.sourceOptions()
    sourceOptions.value = sourceRes.data || []
  } catch (error) {
    console.error('获取选项数据失败:', error)
    ElMessage.error('获取选项数据失败')
  }
}

// 监听客户来源变化
watch(() => formData.value.source, (newVal, oldVal) => {
  console.log('客户来源变化:', oldVal, '->', newVal)
  // 如果有值但选项还没加载，则强制加载选项
  if (newVal && sourceOptions.value.length === 0) {
    loadOptions()
  }
})

// 处理客户类型变化
const handleTypeChange = (value: number) => {
  emit('change', { field: 'customer_type', value })

  // 切换为企业客户时，法定代表人设为必填
  // 切换为个人客户时，清空企业信息
  if (value === 1) {
    formData.value.legal_person = ''
    formData.value.id_type = null
    formData.value.id_number = ''
  }
}

// 处理负责人变化
const handleUserChange = (userId: number) => {
  const user = userList.value.find(u => u.value === userId)
  if (user && user.department_id) {
    formData.value.department_id = user.department_id
  }
  emit('change', { field: 'user_id', value: userId })
}

// 组件挂载时加载数据
onMounted(() => {
  loadOptions()
})
</script>'''

    # 替换script部分
    content = re.sub(
        r'<script setup lang="ts">.*?</script>',
        new_script_basic,
        content,
        flags=re.DOTALL
    )

    with open(basic_file, 'w', encoding='utf-8') as f:
        f.write(content)

    print("✅ BasicInfoForm.vue 修复完成")
    print("   - 添加了watch监听source变化")
    print("   - 确保选项数据加载后再渲染表单")

if __name__ == '__main__':
    fix_form_options_loading()
    print("\n" + "=" * 60)
    print("修复完成！编辑客户表单现在应该能正确显示文字了。")
    print("=" * 60)
